/**
 * Copyright (c) 2025   All rights reserved.
 * <p>
 * https://www.sdl.io
 * <p>
 * 版权所有，侵权必究！
 */

package io.sdl.controller;


import io.sdl.common.utils.Result;
import io.sdl.dto.ChooseRoleDTO;
import io.sdl.entity.RoleUserEntity;
import io.sdl.entity.SysRoleEntity;
import io.sdl.entity.TokenEntity;
import io.sdl.service.RoleUserService;
import io.sdl.service.SysRoleService;
import io.sdl.service.impl.TokenServiceImpl;
import io.sdl.vo.UserInfoVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.Date;

/**
 * 角色管理
 *
 * @authorDc 1211734836@qq.com
 */
@RestController
@RequestMapping("/api")
@Tag(name = "角色管理")
@AllArgsConstructor
public class ApiSysRoleController {

	@Autowired
	private SysRoleService sysRoleService;

	@Autowired
	private TokenServiceImpl tokenServiceImpl;

	@Autowired
	private RoleUserService roleUserService;


	@PostMapping("role")
	@Operation(summary = "获取角色")
	public Result<List<SysRoleEntity>> roleList(@RequestBody ChooseRoleDTO chooseRoleDto) {

		//用户角色集合
		List<SysRoleEntity> sysRoleEntities = new ArrayList<>();

		//获取用户
		TokenEntity byToken = tokenServiceImpl.getByTokenAMobile(chooseRoleDto.getToken(), chooseRoleDto.getMobile());

		//获取所有移动端的角色
		List<SysRoleEntity> sysRoleEntity = sysRoleService.getSysRoleEntity(chooseRoleDto.getPlatform());


		//如果已创建角色
		if (byToken != null) {
			//获取用户所有的角色
			List<RoleUserEntity> list = roleUserService.getRoleUsersByRoleId(byToken.getUserId());

			sysRoleEntity.forEach(a -> {
				if (list.size() > 0) {
					//用户已有角色集合
					list.forEach(roleUserEntity -> {
						if (roleUserEntity.getRoleId().equals(a.getId())) {
							a.setSomeField(1);
						}
					});
				}
				sysRoleEntities.add(a);
			});
		} else {
			sysRoleEntity.forEach(a -> {
				sysRoleEntities.add(a);
			});
		}

		return new Result<List<SysRoleEntity>>().ok(sysRoleEntities);
	}

	@PostMapping("relevance")
	@Operation(summary = "关联角色")
	public Result<UserInfoVo> relevanceRole(@RequestBody ChooseRoleDTO chooseRoleDto) {

		//获取用户信息
		TokenEntity byToken = tokenServiceImpl.getByTokenAMobile(chooseRoleDto.getToken(), chooseRoleDto.getMobile());
		SysRoleEntity roleByRemark = sysRoleService.getRoleByRemark(chooseRoleDto.getIdentifier());

		if(chooseRoleDto.getIdentifier().equals("institutionAdmin")){
			UserInfoVo userInfoVo = new UserInfoVo();
			//需要返回的用户信息
			userInfoVo.setRemark(roleByRemark.getRemark());
			return new Result<UserInfoVo>().ok(userInfoVo);
		}
		RoleUserEntity roleUserEntity = new RoleUserEntity();
		//当前时间
		Date now = new Date();

		//查询是否有关关联
		RoleUserEntity entity = roleUserService.getRoleUserByRoleIdAndUserId(roleByRemark.getId(), byToken.getUserId());


		//没有则关联
		if (entity == null) {
			//查询是否拥有其他角色
			List<RoleUserEntity> roleList = roleUserService.getRoleUsersByRoleId(byToken.getUserId());
//			if (roleList.size() > 0) {
//				return new Result<UserInfoVo>().error(400, "每个微信号最多只能拥有一个角色");
//			}
			roleUserEntity.setUserId(byToken.getUserId());
			roleUserEntity.setRoleId(roleByRemark.getId());
			roleUserEntity.setCreateDate(now);
			roleUserService.insert(roleUserEntity);
		}

		UserInfoVo userInfoVo = new UserInfoVo();
		//需要返回的用户信息
		userInfoVo.setRemark(roleByRemark.getRemark());

		return new Result<UserInfoVo>().ok(userInfoVo);
	}


	@PostMapping("role/unbind")
	@Operation(summary = "解绑角色")
	public Result<UserInfoVo> unbindRole(@RequestBody ChooseRoleDTO chooseRoleDto) {
		//获取用户信息
		TokenEntity byToken = tokenServiceImpl.getByToken(chooseRoleDto.getToken());

		if (byToken != null) {
			if(chooseRoleDto.getRoleId()!=null){
				//删除对应角色和用户关联
				roleUserService.unbindRole(byToken.getUserId(), Long.parseLong(chooseRoleDto.getRoleId()));
			}else{
				SysRoleEntity roleByRemark = sysRoleService.getRoleByRemark(chooseRoleDto.getIdentifier());
				//删除对应角色和用户关联
				roleUserService.unbindRole(byToken.getUserId(), roleByRemark.getId());
			}


			return new Result().ok("解绑成功");
		}
		return new Result().error(400, "长时间未操作,请重新登录");
	}


}
